<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/admin/AdminAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/DepartmentType.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Error.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class DepartmentTypeUpdateAction extends AdminAction {
	protected function execute(Response $response) {
		if(isset($_POST['name']) && Str::isMatch(Pattern::WORD, $_POST['name'])) {
			$type = new DepartmentType();
			$type->setName($_POST['name']);
			$type->setIdPost($_POST['idPost']);
			$serviceFactory = new ServiceFactory();
			$service = $serviceFactory->getService('DepartmentTypeService');
			
			if($_POST['identity']) {
				$type->setIdentity($_POST['identity']);	
			}
			$type = $service->save($type);
			if($type === null) {
				$response->setError(Error::UNIQUE_DEPARTMENT_TYPE_ERROR);
			}
		}
		if($response->getError() === null) {
			$response->setActionPath('/departmenttype/index.html');
		}
	}
}
?>